<!DOCTYPE html>
<html>
  <head>
    <title>WebSocket Client</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

    <script type="text/javascript">
    var ws;
    function connect(obj){
        // 创建一个Socket实例
        ws = new WebSocket('ws://localhost:9999/connect?token=1q2w3e4r&deviceId=001'); 
        // 打开Socket 
        ws.onopen = function(event) {
            $("#log").append("客户端成功连接\n");
            $("#connect").attr("disabled",true);
        };
        // 监听Socket的消息
        ws.onmessage = function(event) { 
            $("#log").append("客户端收到的消息："+event.data+"\n");
        }; 

        // 监听Socket的关闭
        ws.onclose = function(event) { 
            $("#log").append("客户端被告知socket关闭了\n");
        }; 

        // 关闭Socket.... 
        // socket.close() 
    }
    function send(){
        if (ws) {
            var msg = "hello 我是客户端~~";
            $("#log").append("客户发送的消息：" + msg + "\n");
            ws.send(msg);
        }
    }
    </script>
  </head>
  <body>
      <input type="button" id="connect" value="Connect" onclick="connect(this)"><br/>
      <input type="button" value="Send" onclick="send()"><br/>
      <textarea id="log" rows="30" cols="100"></textarea><br/>
  </body>
</html>
